package com.example.util;

/**
 * @author ：伍绍恒
 * @date ：Created in 2023/6/6 17:06
 * @description：Excel export
 * @modified By：
 */

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: computer
 * @packageName: com.wzh.utils
 * @author: xmhz45
 * @create: 2022/7/6 19:31
 */
public class ExcelUtil {

    public void export(String filename, List objects, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //防止中文乱码
            // 获取当前时间
            Date now = new Date();
            // 设置日期格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
            // 格式化日期
            String currentTime = dateFormat.format(now);
            String fileName = new String(filename.getBytes("UTF-8"), "ISO-8859-1") + " " + currentTime;
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            //response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            //获取流对象
            ServletOutputStream outputStream = response.getOutputStream();
            //工作簿对象
            ExcelWriterBuilder writerWork = EasyExcel.write(outputStream, objects.get(0).getClass());
            //工作表对象
            ExcelWriterSheetBuilder sheet = writerWork.sheet("sheet1");
            sheet.doWrite(objects);
            //输出全部流
            outputStream.flush();
            //关闭流
            outputStream.close();

        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            e.printStackTrace();

        }
    }
    //    public int importExcel(Class<T> t, MultipartFile multipartFile, )

}